package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-08-09
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {
    @Autowired
    private MinIOService minIOService;
    //素材管理-图片上传
    public ResponseResult<WmMaterial> upload(MultipartFile file) {
        // 用户id从本地线程中获取
        User user = MediaThreadLocalUtil.get();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 调用minio上传图片,获取url地址
        String url = minIOService.upload(file);
        // 构建素材对象,存入到数据库中
        WmMaterial wmMaterial=new WmMaterial();
        wmMaterial.setUrl(url);
        wmMaterial.setUserId(user.getUserId());
        wmMaterial.setType(0);
        wmMaterial.setIsCollection(false);
        wmMaterial.setCreatedTime(new Date());
        this.save(wmMaterial);

        return ResponseResult.okResult(wmMaterial);
    }

    //素材管理-素材列表
    public ResponseResult listByCollection(WmMaterialDto dto) {
        // 获取当前用户的id
        User user = MediaThreadLocalUtil.get();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建查询条件
        LambdaQueryWrapper<WmMaterial> query=new LambdaQueryWrapper<>();
        //判断是否传入了收藏状态
        if (dto.getIsCollection()!=null) {
            query.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //当前用户只能查询自己照片
        query.eq(WmMaterial::getUserId,user.getUserId());
        //对结果进行倒叙排列，按照创建时间
        query.orderByDesc(WmMaterial::getCreatedTime);
        //构建分页条件
        IPage<WmMaterial> iPage=new Page<>(dto.getPage(),dto.getSize());
        //分页查询
        IPage<WmMaterial> page = this.page(iPage, query);

        // 构建通用的分页响应
        PageResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(),iPage.getTotal(),iPage.getRecords());
        return result;
    }
}
